package net.vinote.smart.platform.service.handler;

import java.sql.SQLException;

import net.vinote.smart.platform.exception.PlatformException;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.service.dw.handler.CommonHandler;
import net.vinote.smart.platform.service.dw.handler.HandlerPerimissionAnnotation;
import net.vinote.smart.platform.service.enumerate.CodeCatalogEnum;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

import org.apache.commons.lang.math.NumberUtils;

@HandlerPerimissionAnnotation(
		insert = @Permission(PermissionEnum.SMART_CODE_LIBRARY_INSERT),
		update = @Permission(PermissionEnum.SMART_CODE_LIBRARY_UPDATE),
		query = @Permission(PermissionEnum.SMART_CODE_LIBRARY_QUERY),
		delete = @Permission(PermissionEnum.SMART_CODE_LIBRARY_DELETE))
public class CodeLibraryHandler extends CommonHandler {
	@Override
	public void initDisplayForAdd(BizObject bo) {
		String codNo = request.getParameter("codeNo");
		setDefaultValue("CodeNo", codNo);
	}

	@Override
	public void initDisplayForEdit(BizObject bo) {
		setReadOnly("ItemNo", true);
	}

	@Override
	protected void beforeDelete(BizObject bo, DBTransaction tx)
			throws SQLException {
		String codeNo = bo.getAttribute("CodeNo");
		String itemNo = bo.getAttribute("ItemNo");
		CodeCatalogEnum catalogEnum = CodeCatalogEnum.getCodeCatalog(codeNo);
		if (catalogEnum == null) {
			return;
		}
		switch (catalogEnum) {
		case AppInfoSubject:
			checkAppInfoSubject(tx, itemNo);
			break;
		default:
			break;
		}
	}

	/**
	 * 校验子系统栏目是否可删除
	 * 
	 * @param itemNo
	 * @throws SQLException
	 */
	private void checkAppInfoSubject(DBTransaction tx, String itemNo)
			throws SQLException {
		DBManager bm = new DBManager("app_info");
		tx.join(bm);
		BizObject bo = bm
				.createQuery(new String[] { "count(*) as appCount" },
						"subject=?").setParamVal(itemNo).getSingleResult();
		int appCount = NumberUtils.toInt(bo.getAttribute("appCount"));
		if (appCount > 0) {
			throw new PlatformException("当前子系统下还存在" + appCount + "个应用,不可删除!");
		}

		bm = new DBManager("layout_catalog");
		tx.join(bm);
		bo = bm.createQuery(new String[] { "count(*) as layoutCount" },
				"subject=?").setParamVal(itemNo).getSingleResult();
		int layoutCount = NumberUtils.toInt(bo.getAttribute("layoutCount"));
		if (layoutCount > 0) {
			throw new PlatformException("当前子系统下还存在" + layoutCount
					+ "个布局,请先清理布局管理中的数据!");
		}
	}
}
